package com.cym.service;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cym.config.SqlConfig;
import com.cym.ext.GroupExt;
import com.cym.ext.UserExt;
import com.cym.model.Repository;
import com.cym.model.User;

import cn.craccd.sqlHelper.utils.SqlHelper;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;

@Service
public class ConfigService {
	@Autowired
	SqlHelper sqlHelper;
	@Autowired
	SqlConfig sqlConfig;
	@Autowired
	RepositoryService repositoryService;
	@Autowired
	GroupService groupService;

	public void refresh() {
		List<String> lines = new ArrayList<>();
		List<Repository> repositories = sqlHelper.findAll(Repository.class);
		for (Repository repository : repositories) {
			String svnserve_conf = sqlConfig.home + "/repo/" + repository.getName() + "/conf/svnserve.conf";
			String passwd = sqlConfig.home + "/repo/" + repository.getName() + "/conf/passwd";
			String authz = sqlConfig.home + "/repo/" + repository.getName() + "/conf/authz";

			// 基础配置
			lines.clear();
			lines.add("[general]");
			lines.add("anon-access=none");
			lines.add("auth-access=write");
			lines.add("password-db=passwd");
			lines.add("auth-db=authz");
			lines.add("[sasl]");
			FileUtil.writeLines(lines, svnserve_conf, Charset.forName("UTF-8"));

			// 用户名密码
			lines.clear();
			lines.add("[users]");
			List<User> userList = sqlHelper.findAll(User.class);
			for (User user : userList) {
				lines.add(user.getName() + "=" + user.getPass());
			}
			FileUtil.writeLines(lines, passwd, Charset.forName("UTF-8"));

			// 组和权限
			lines.clear();
			lines.add("[groups]");
			List<GroupExt> groups = repositoryService.getGroupExts(repository.getId());
			for (GroupExt groupExt : groups) {
				String groupStr = groupExt.getName() + "=";
				List<User> users = groupService.getUserList(groupExt.getId());
				List<String> names = users.stream().map(User::getName).collect(Collectors.toList());
				groupStr += StrUtil.join(",", names);
				lines.add(groupStr);
			}
			lines.add("[/]");
			for (GroupExt groupExt : groups) {
				lines.add("@" + groupExt.getName() + "=" + groupExt.getPermission());
			}
			List<UserExt> userExts = repositoryService.getUserExts(repository.getId());
			for (UserExt userExt : userExts) {
				lines.add(userExt.getName() + "=" + userExt.getPermission());
			}
			FileUtil.writeLines(lines, authz, Charset.forName("UTF-8"));
		}
	}

}
